<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, nextTick } from 'vue'
import defaultSettings from '@/settings'
import { getToken } from '@/utils/auth'
import { getCacheDict } from '@base/api/base/dict/type'
import { searchAppByPage, selectAppById, insertApp, updateAppById } from '@code/api/application'
import { listAppAll } from '@uni/api/uni/app/info'
import { getPinyin } from '@/api/common'
import { resetFormPlus, getCustomUploadTrans, selectDictLabel } from '@/utils/zmids'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

interface Form {
  codeAppName: string
  codeAppCode: string
  codeAppDesc: string
  codeAppLogo: string
  codeAppColor: string
  codeAppSysId: string
}

interface SystomOption {
  appId: string
  appName: string
  [key: string]: string
}

const loading = ref(false)

const form = ref<Form>({
  codeAppName: '',
  codeAppCode: '',
  codeAppDesc: '',
  codeAppLogo: '',
  codeAppColor: '',
  codeAppSysId: ''
})

const formRef = ref<FormInstance>()

const queryForm = ref<FormInstance>()

const tableData = ref([])

const total = ref(0)

const title = ref('')

const type = ref('add')

const showDialog = ref<Boolean>(false)

const showSearch = ref<Boolean>(true)

const stateOptions = ref([])

const systemOptions = ref<SystomOption[]>([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderBy: 'UPDATE_TIME',
  sortDirect: 'DESC',
  isDelete: 'N',
  codeAppName: undefined,
  codeAppCode: undefined,
  codeAppSysId: undefined,
  codeAppStatus: undefined
})

const rules = {
  codeAppName: [{ required: true, message: '应用名称不能为空', trigger: 'blur' }],
  codeAppCode: [{ required: true, message: '应用编码不能为空', trigger: 'blur' }],
  codeAppSysId: [{ required: true, message: '所属系统不能为空', trigger: 'blur' }]
}

const url =
  import.meta.env.VITE_APP_BASE_API +
  (defaultSettings.isCould ? '/system-service' : '') +
  '/custom/upload'

const predefineColors = [
  '#FF4500',
  '#FF8C00',
  '#FFD700',
  '#90EE90',
  '#00CED1',
  '#409EFF',
  '#C71585'
]

const headers = computed(() => {
  return {
    [defaultSettings.tokenName]: 'Bearer ' + getToken()
  }
})

const chineseTrans = (value: string) => {
  nextTick(() => {
    if (value) {
      getPinyin(value).then((res) => {
        form.value.codeAppCode = res.data
      })
    } else {
      form.value.codeAppCode = ''
    }
  })
}

const handleAvatarSuccess = (res, file) => {
  const obj = getCustomUploadTrans(res.data)
  form.value.codeAppLogo = obj!.url
}

const getList = () => {
  return searchAppByPage(queryParams).then((res: any) => {
    tableData.value = res.data.list
    total.value = res.data.total
  })
}

const initForm = () => {
  resetFormPlus(formRef.value)
  form.value = {
    codeAppName: '',
    codeAppCode: '',
    codeAppDesc: '',
    codeAppLogo: '',
    codeAppColor: '',
    codeAppSysId: ''
  }
}

const handleDownlineClick = (data: any) => {
  const params = {
    ...data,
    codeAppStatus: data.codeAppStatus == 'Y' ? 'N' : 'Y'
  }
  ElMessageBox.confirm('确定要修改状态吗？', '状态修改', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateAppById(params)
      .then((res: any) => {
        ElMessage.success('状态修改成功')
        getList()
      })
      .catch(function () { })
  })
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  resetFormPlus(queryForm.value)
  handleQuery()
}

const handleAdd = () => {
  initForm()
  showDialog.value = true
  title.value = '新增应用'
  type.value = 'add'
}

const handleStatusChange = (row: any) => {
  row.codeAppStatus = row.codeAppStatus === 'Y' ? 'N' : 'Y'
  let text = row.codeAppStatus === 'Y' ? '启用' : '禁用'
  updateAppById(row)
    .then((response) => {
      if (response.data === 1) {
        ElMessage.success(text + '成功')
      } else {
        ElMessage.error(text + '失败')
      }
      getList()
    })
    .catch((e) => {
      console.error(e)
    })
}

const handleUpdate = (row: any) => {
  selectAppById(row.codeAppId).then((response) => {
    form.value = response.data
    type.value = 'update'
    title.value = '修改应用'
    showDialog.value = true
  })
}

const handleDetails = (row: any) => {
  selectAppById(row.codeAppId).then((response) => {
    form.value = response.data
    type.value = 'detail'
    title.value = '应用详情'
    showDialog.value = true
  })
}

const handleDelete = (row: any) => {
  const params = {
    ...row,
    isDelete: 'Y'
  }
  updateAppById(params)
    .then((res) => {
      ElMessage.success('删除成功')
      getList()
    })
    .catch(function () { })
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  formEl.validate((valid) => {
    if (valid) {
      if (type.value == 'update') {
        updateAppById(form.value).then((response) => {
          if (response.data === 1) {
            ElMessage.success('修改成功')
            showDialog.value = false
            getList()
          }
        })
      } else {
        insertApp(form.value).then((response) => {
          if (response.code === '200') {
            ElMessage.success('新增成功')
            showDialog.value = false
            getList()
          }
        })
      }
    }
  })
}

const cancel = () => {
  showDialog.value = false
  initForm()
}

const getSystemOptions = () => {
  return listAppAll().then((res) => {
    systemOptions.value = res.data
  })
}

const getSystemOptLabel = (value: string) => {
  return systemOptions.value.find((opt) => opt.appId == value)?.appName ?? ''
}

const init = () => {
  getList()
  getSystemOptions()
  getCacheDict('sys_normal_disable').then((response: any) => {
    stateOptions.value = response.data
  })
}

init()
</script>

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用名称" prop="codeAppName">
        <el-input v-model="queryParams.codeAppName" placeholder="请输入应用名称" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="应用编码" prop="codeAppCode">
        <el-input v-model="queryParams.codeAppCode" placeholder="请输入应用编码" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属系统" prop="codeAppSysId">
        <el-select v-model="queryParams.codeAppSysId" placeholder="选择所属系统" clearable size="default"
          style="width: 240px">
          <el-option v-for="dict in systemOptions" :key="dict.appId" :label="dict.appName" :value="dict.appId" />
        </el-select>
      </el-form-item>
      <el-form-item label="应用状态" prop="codeAppStatus">
        <el-select v-model="queryParams.codeAppStatus" placeholder="应用状态" clearable size="default" style="width: 240px">
          <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" />
        <reset-button @click="resetQuery" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" />
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="应用名称" align="center" prop="codeAppName" width="260" />
      <el-table-column label="应用编码" align="center" prop="codeAppCode" width="260" />
      <el-table-column label="应用描述" align="center" prop="codeAppDesc" width="260" />
      <el-table-column label="所属系统" align="center" width="260">
        <template #default="scope">
          {{ getSystemOptLabel(scope.row.codeAppSysId) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="codeAppStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tag :type="scope.row.codeAppStatus == 'Y' ? 'success' : 'danger'">
            {{ scope.row.codeAppStatus == 'Y' ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" width="100" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="400">
        <template #default="scope">
          <text-disable-button v-if="scope.row.codeAppStatus === 'Y'" @click="handleStatusChange(scope.row)"
            :title="'是否确认禁用' + scope.row.codeAppName" />
          <text-enable-button v-else-if="scope.row.codeAppStatus === 'N'" @click="handleStatusChange(scope.row)"
            :title="'是否确认启用' + scope.row.codeAppName" />
          <text-edit-button @click="handleUpdate(scope.row)" />
          <el-button link class="operate-button" v-if="scope.row.codeAppStatus == 'N'"
            @click="handleDownlineClick(scope.row)">上线</el-button>
          <el-button link class="operate-button" v-else @click="handleDownlineClick(scope.row)">下线</el-button>
          <text-detail-button @click="handleDetails(scope.row)" text="详细" />
          <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.codeAppName + '?'" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <drag-dialog v-el-drag-dialog :title="title" :close-on-click-modal="false" v-model="showDialog" width="1200px"
      append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" :disabled="type == 'detail'">
        <el-form-item label="应用名称" prop="codeAppName">
          <el-input v-model="form.codeAppName" placeholder="请输入应用名称" @input="chineseTrans" />
        </el-form-item>
        <el-form-item label="应用编码" prop="codeAppCode">
          <el-input v-model="form.codeAppCode" placeholder="请输入应用编码" />
        </el-form-item>
        <el-form-item label="所属系统" prop="codeAppSysId">
          <el-select v-model="form.codeAppSysId" placeholder="请选择所属系统">
            <el-option v-for="(opt, idx) in systemOptions" :key="idx" :label="opt.appName" :value="opt.appId" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用描述" prop="codeAppDesc">
          <el-input type="textarea" v-model="form.codeAppDesc" placeholder="请输入应用描述" />
        </el-form-item>
        <el-form-item label="门户Logo">
          <el-upload class="avatar-uploader" :headers="headers" :action="url" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="form.codeAppLogo" :src="form.codeAppLogo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="门户主色系">
          <el-color-picker v-model="form.codeAppColor" :predefine="predefineColors" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :disabled="type == 'detail'" @click="submitForm(formRef)">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </drag-dialog>
  </div>
</template>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px !important;
  color: #8c939d !important;
  width: 178px !important;
  height: 178px !important;
  line-height: 178px !important;
  text-align: center !important;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
